<?php

namespace App\Admin\Controllers;

use App\Models\Device;
use App\Models\Project;
use App\Models\ProjectPlan;
use App\Models\DeviceType;
use App\Models\SwitchData;
use App\Http\Controllers\Controller;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Widgets\Callout;
// use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Dcat\Admin\Form;
use Dcat\Admin\Admin;
use Dcat\Admin\Show;
use Log;
use SuperEggs\DcatDistpicker\Form\Distpicker;
use Illuminate\Http\Request;
use Dcat\Admin\Widgets\Tab;
use App\Models\ProjectUser;
use Dcat\Admin\Form\NestedForm;
// use App\Admin\Extensions\Form\ApiSelect\ApiSelect;
use App\Handlers\WeconHandler;
use App\Admin\Actions\Modal\deviceModal;
use App\Admin\Actions\Modal\SmokeRegister;


class DeviceController extends Controller
{

    public function index(Content $content)
    {
        return $content
            ->header('设备列表')
            ->description()
//            ->body(Callout::make('即将在下个版本发布，敬请期待~'))
            ->body($this->grid());
    }

    public function Pdevice($id,Content $content){
        return $content
            ->header('设备列表')
            ->description()
            ->body($this->grid($id));
    }

    protected function grid($id = 0)
    {
        // $tab = Tab::make();

// 第一个参数是选项卡标题，第二个参数是内容，第三个参数是是否选中
// $tab->add('选项卡1', view('...'), true);
// $tab->add('选项2', 'html');
// $tab->add('选项3', 'html11111');
// 添加选项卡链接
// $tab->addLink('跳转链接', 'http://xxx');
// return$tab->withCard()->vertical();
        if (!$id) {
            $projectIds = ProjectUser::where('user_id', Admin::user()->id)->pluck('projectId')->toArray();
            $device = Device::whereIn('projectId', $projectIds)->pluck('deviceId');
        } else {
            $device = Device::where('projectId', $id)->pluck('deviceId');
        }
        return new Grid(Device::whereIn('deviceId',$device)->where('pid','0'), function (Grid $grid) {
            $grid->showColumnSelector();

            $grid->column('devicename','设备名称');

            // $grid->column('devicename','设备名称')->limit(50)->link(function ($device_type) {
            //     return admin_url('DeviceCabinet/'.$this->getKey());
            // });

            // $grid->devicename->tree();
            $grid->column('deviceId','ID');
            $grid->column('cid','设备ID');
            $grid->column('group','分组IP');
            $grid->column('gatewayId','电信平台设备编号');
            $grid->column('address','设备地址');
            $grid->column('created_at','创建时间');
            // $grid->column('user_id','创建人')->display(function($userId) {
            //     return Db::table('admin_users')->where(['id'=>$userId])->value('name');;
            // });
            $grid->column('companyId','公司')->display(function($companyId) {
                return Db::table('xfy_company')->where(['companyId'=>$companyId])->value('name');;
            });
            $grid->column('lat','纬度');
            $grid->column('lng','经度');
            $grid->column('heartbeat',trans('状态'))->using(['0'=>'离线','1'=>'在线']);
            // 启用边框模式
            $grid->withBorder();
            $grid->fixColumns(2);
            //操作按钮
            $grid->showActions();
            // $grid->disableActions();
            // $grid->disableBatchDelete();
            $grid->disableCreateButton();
            $url = admin_base_path('Device/create');
            $grid->tools("<a href='$url' class='btn btn-primary btn-outline'><i class='feather'>新增设备</a>");
            // 禁用详情按钮
            $grid->disableViewButton();
            // 显示详情按钮
            // $grid->showViewButton();
            // 禁用编辑按钮
            $grid->disableEditButton();
            // 显示编辑按钮
            // $grid->showEditButton();
            // 禁用快捷编辑按钮
            $grid->disableQuickEditButton();
            // 显示快捷编辑按钮
            // $grid->showQuickEditButton();
            // 设置弹窗宽高，默认值为 '700px', '670px'
            $grid->setDialogFormDimensions('50%', '50%');
            // 禁用删除按钮
            // $grid->disableDeleteButton();
            // 显示删除按钮
            $grid->showDeleteButton();
            $grid->disableBatchDelete();
             
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $id = $actions->getKey();
                // $plan = $actions->getPlanJPG();
                // var_dump($actions->row->planeJPG);die;
                $edit_url = admin_base_path('Device/'.$id.'/edit');
                // $location_url = admin_base_path('Device/location/'.$id);
                $actions->append("<a href='$edit_url'><i class='feather icon-edit-1 grid-action-icon'></i></a>");
                // $actions->append("<a href='$edit_url'><i class='feather icon-edit-1 grid-action-icon'></i></a>");
                $actions->append('<a href="/admin/DeviceCabinet/'.$id.'"><i class="fa fa-eye"></i></a>');
                if($actions->row->planeJPG){
                    $actions->prepend('<a href="/admin/device/location/'.$actions->row->planeJPG.'"><i class="fa fa-paper-plane"></i></a>');
                }
            });
            $grid->tools(function  (Grid\Tools  $tools)  { 
                //Excel导入
                $tools->append(new deviceModal());  
                $tools->append(new SmokeRegister());  
            });
        });
    }

    public function location($id,Content $content){
        // $device = Device::where(['deviceId'=>$id])->first()->toArray();
        $device = Device::where(['planeJPG'=>$id])->get(['deviceId as rid','devicename as text','color','pageX','pageY','planeJPG','projectId'])->toArray();
        $plane = ProjectPlan::where(['id'=>$id])->first();
        $res = ProjectPlan::where('project_id',$plane['project_id'])->get(['name','id'])->toArray();
        return $content
            ->header($plane['name'].'设备位置')
            ->body(view('admin.device.location',['planeJPG'=>'/uploads/'.$plane['image'],'data'=>json_encode($device),'list'=>$res]));
    }
    public function locationSave(Request $request){
        $info = $request->all();
        foreach($info['data'] as $val){
            $arr = json_decode($val,1);
            Device::where(['deviceId'=>$arr['id']])->update(['pageX'=>$arr['pageX'],'pageY'=>$arr['pageY']]);
        }
        return array('resultCode'=>1,'resulMsg'=>'保存成功!');
    }

    public function update($id){
        return $this->form()->update($id);
    }
    public function store(){
        return $this->form()->store();
    }

    public function destroy($id){
        return $this->form()->destroy($id);
    }

    public function create(Content $content){
        return $content
            ->title('新增设备')
            ->description('创建')
            ->body($this->form());
    }

    public function planeSelect(Request $request){
        $q = $request->get('q');
        return ProjectPlan::where('project_id', $q)->get(['id', DB::raw('image as text')]);
    }

    public function form(){
        return Form::make(new Device(), function (Form $form) {
            $form->text('cid','设备ID');
            $form->hidden('gatewayId','平台编号');
            $form->text('devicename','设备名称')->required();
            $form->distpicker(['province', 'city', 'area']);
            $form->text('address','设备地址');
            //授权项目
            $list = ProjectUser::where('user_id',Admin::user()->id)->pluck('projectId');
            $res = Project::whereIn('projectId',$list)->pluck('projectname','projectId');
            $form->select('projectId','所在项目')->options($res)->required()->load('planeJPG', '/planeSelect');
            $form->select('planeJPG','位置底图');
            $device_type = DeviceType::pluck('typename','dtypeId');
            $form->select('device_type','设备类型')->options($device_type)->required();

            $form->saving(function (Form $form) {
                // $data = $form->updates();
                // 判断是否是新增操作
                if($form->device_type==1&&$form->isCreating()){ //霍尼烟感
                    if(!Cache::has('authtoken')){
                        authentication();
                    }
                    $imei = $form->cid;
                    $dtype = 'GDHS90BWNB';
                    $manu = 'Hisense';
                    $devicetype = 'Smoke';
                    $url = 'https://device.api.ct10649.com:8743/iocm/app/reg/v1.1.0/deviceCredentials?appId=86y97uYn78Try5i1zFdTLiErnX4a';
                    $header = array('Content-Type:application/json','Authorization:Bearer '.Cache::get('authtoken'),'app_key:86y97uYn78Try5i1zFdTLiErnX4a');
                    $data = '{"verifyCode":"'.$imei.'","nodeId":"'.$imei.'","deviceInfo":{"manufacturerId":"'.$manu.'","manufacturerName":"'.$manu.'","deviceType":"'.$devicetype.'","model":"'.$dtype.'","protocolType":"CoAP"}}';
                    $curl = curl_init(); // 启动一个CURL会话
                    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
                    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); // 对认证证书来源的检查
                    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);// 从证书中检查SSL加密算法是否存在
                    curl_setopt($curl, CURLOPT_SSLCERT,dirname(dirname(dirname(__FILE__))).'/server.crt');
                    curl_setopt($curl, CURLOPT_SSLKEY, dirname(dirname(dirname(__FILE__))).'/server.key');
                    curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
                    curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 显示返回的Header区域内容
                    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
                    $res = curl_exec($curl); // 执行操作
                    $ret = ['status' => 1];
                    if ($error = curl_errno($curl)) {
                        $ret['status'] = 0;
                        $ret['return'] = $error;
                    } else {
                        $ret['return'] = $res;
                    }
                    curl_close($curl); // 关闭CURL会话
                    $res = json_decode($ret['return'],1);
                    $form->gatewayId = $res['deviceId'];
                    //Log::info($ret);
                    if($ret['status']!=1){
                        return $form->response()->error('添加电信平台失败~');
                    }else{
                        if(isset($res['error_code'])){
                            return $form->response()->error($res['error_desc']);
                        }
                    }
                }

                // 删除用户提交的数据
                // $form->deleteInput('type');

                // 中断后续逻辑
                // return $form->response()->error('服务器出错了~');
            });
        });

    }
    // //鉴权
    // public function authentication(){
    //     $data = 'appId=86y97uYn78Try5i1zFdTLiErnX4a&secret=aayy3kB2YJGh1FCpeyxGsyC_uCAa';
    //     $url = 'https://device.api.ct10649.com:8743/iocm/app/sec/v1.1.0/login';
    //     $header = ["Content-Type" => "application/x-www-form-urlencoded;"];//貌似不需要,默认就是
    //     $a = $this->postSsl($url,$data,$header);
    //     if($a['status']==1){
    //         $return = json_decode($a['return'],1);
    //         Cache::add('authtoken', $return['accessToken'], 3000);
    //     }
    // }
    // function postSsl($url, $data, $header) {
    //     //if (is_array($data)) {
    //     //    $data = http_build_query($data);
    //     //}
    //     $curl = curl_init(); // 启动一个CURL会话
    //     curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    //     curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); // 对认证证书来源的检查
    //     curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);// 从证书中检查SSL加密算法是否存在
    //     curl_setopt($curl, CURLOPT_SSLCERT,dirname(dirname(dirname(__FILE__))).'/server.crt');
    //     curl_setopt($curl, CURLOPT_SSLKEY, dirname(dirname(dirname(__FILE__))).'/server.key');
    //     curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
    //     curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    //     curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // 显示返回的Header区域内容
    //     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    //     $res = curl_exec($curl); // 执行操作
    //     $ret = ['status' => 1];
    //     if ($error = curl_errno($curl)) {
    //         $ret['status'] = 0;
    //         $ret['return'] = $error;
    //     } else {
    //         $ret['return'] = $res;
    //     }
    //     curl_close($curl); // 关闭CURL会话
    //     return $ret; // 返回数据
    // }
    public function show($id){
        return Show::make($id, new Device(), function (Show $show) {
            $show->field('cid','设备ID');
            $show->field('gatewayId','平台编号');
            $show->field('address','设备地址');
            $show->field('lat','纬度');
            $show->field('lng','经度');
            $show->created_at;
        });
    }

    public function edit($id,Content $content){
        return $content
            ->title('设备编辑')
            ->description('编辑')
            ->body($this->form()->edit($id));
    }
}